<template>
    <div class="homeHeader">
        <div class="title" style="width:100%">
            <i @click="toHomePage">TIM</i>
            <el-dropdown class="userInfo" @command="fnCommand">
        <span class="el-dropdown-link">
          <span>{{ userInfo.name }}</span>
            <div style="margin-left: 15px">
                <el-badge class="mark" :is-dot="messageNum>0">
                  <el-avatar size="large" :src="userInfo.userFace"></el-avatar>
                </el-badge>
            </div>
        </span>
                <el-dropdown-menu>
                    <template #dropdown/>
                    <el-dropdown-item command="消息">消息
                        <el-badge class="mark" :max="99" :value="messageNum"/>
                    </el-dropdown-item>
                    <el-dropdown-item command="个人中心">个人中心</el-dropdown-item>
                    <el-dropdown-item command="设置">设置</el-dropdown-item>
                    <el-dropdown-item command="注销登录">注销登录</el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </div>
        <el-drawer
                :title="rightDrawer.title"
                :visible.sync="rightDrawer.drawer"
                direction="rtl">
            <personal-center v-if="rightDrawer.drawer && rightDrawer.title === '个人中心'"/>
            <message v-if="rightDrawer.drawer && rightDrawer.title === '消息'"/>
        </el-drawer>
    </div>
</template>

<script>

import PersonalCenter from "@/views/home/compoents/compoents/PersonalCenter.vue";
import Message from "@/views/home/compoents/compoents/message/Message.vue";

export default {
    name: "HomeHeader",
    components: {Message, PersonalCenter},
    data() {
        return {
            //用户信息
            userInfo: this.$store.getters.app.userInfo,
            //api
            api: this.$store.getters.app.api,
            //个人中心数据
            personalCenter: {},
            //退出登录
            logout: 'logout',
            //消息数
            messageNum: 0,
            //个人设置数据
            personalSettings: {},
            //右侧抽屉
            rightDrawer: {
                drawer: false,
                title: null

            }
        }
    },
    created() {
        this.init();
    },
    mounted() {
    },
    methods: {
        /**
         * 回到主页面
         */
        toHomePage() {
            this.$router.replace('/home')
        },
        /**
         * 退出登录
         * @param command
         */
        async fnCommand(command) {
            //console.log(command)
            if (command === '注销登录') {
                await this.$confirm("你确定要退出吗？( ╯□╰ )，是否继续？", "退出提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    //退出登录先从后台去除该用户websocket的连接和rabbitMQ的监听
                    await this.api.article.articleLogOut({userName: this.userInfo.username})
                    this.api.auth.removeToken();
                    this.api.auth.removeUserInfo();
                    this.api.auth.removeRouters();
                    this.$store.commit('app/setRoutes', [])
                    this.$store.commit('app/setUserInfo', null)
                    this.$router.replace('/')
                    // })
                }).catch(() => {
                    this.$message.info('已取消操作！')
                })
            } else if(command === '设置'){
                this.$router.replace('/modules/sys/sysAdmin')
            }else {
                if (command === '消息') {
                    this.messageNum = 0
                }
                this.rightDrawer = {
                    drawer: true,
                    title: command
                }
            }
        },
        /**
         * 初始化连接websocket
         */
        init() {
            let that = this
            //console.log("正在连接 ......");

            if (!window.WebSocket) {
                window.WebSocket = window.MozWebSocket;
            }
            if (window.WebSocket) {
                this.socket = new WebSocket("ws://localhost:1234/ws");
                //消息返回事件
                this.socket.onmessage = function (event) {
                    //console.log("onmessage", event)
                    that.socketOnmessage(event.data)
                }
                //开启连接
                this.socket.onopen = function (event) {
                    //console.log("onopen", event)
                    sessionStorage.setItem("socket", JSON.stringify(that.socket));
                    that.send();
                };
                //关闭连接
                this.socket.onclose = function (event) {
                    //console.log("onclose", event)
                };
            } else {
                //console.log("您的浏览器不支持WebSocket协议！");
            }
        },
        /**
         * 用户连接
         */
        send() {
            let message = '{"userId":"' + this.userInfo.username + '"}'
            if (this.socket.readyState == WebSocket.OPEN) {
                this.socket.send(message);
                //console.log("连接成功！")
            } else {
                alert("WebSocket 连接没有建立成功！");
            }
        },
        /**
         * 获取到socket的消息处理
         * @param data
         */
        socketOnmessage(data) {
            let res = JSON.parse(data);
            if (res.data.noticeCount) {
                this.messageNum += parseInt(res.data.noticeCount);
            }
            if (res.data.notice) {
                let notice = JSON.parse(res.data.notice);
                this.messageNum += notice.cancelOrConfirm
            }
            if (this.messageNum < 0) this.messageNum = 0
            //console.log("this.messageNum => ", this.messageNum)
        },
    }
}
</script>

<style scoped>

.homeHeader {
    background-color: black;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;
    box-sizing: border-box;
    height: 60px;
    width: 100%;
    left: 0px;
}

.homeHeader .title {
    margin: auto;
    text-align: center;
}

.homeHeader .title i {
    font-size: 30px;
    font-family: 华文楷体;
    color: #FFFFFF;
}

.homeHeader .userInfo {
    cursor: pointer;
    float: right;
    margin-top: 10px;
}

.el-aside {
    background: #ffffff1f;
    position: fixed;
    top: 60px;

}

.el-dropdown-link {
    display: flex;
    align-items: center;
}

.el-dropdown {
    color: #c5c5c5;
}

</style>
